package top.jacktgq.itheima.netty.protocol_design.groupchat.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;
import top.jacktgq.itheima.netty.protocol_design.groupchat.server.handler.ServerMessageHandler;
import top.jacktgq.itheima.netty.protocol_design.groupchat.protocol.MessageCodecSharable;
import top.jacktgq.itheima.netty.protocol_design.groupchat.protocol.ProtocolFrameDecoder;

/**
 * @Author CandyWall
 * @Date 2021/3/24--13:38
 * @Description 聊天服务器
 */
@Slf4j
public class ChatServer {
    public static void main(String[] args) {
        LoggingHandler loggingHandler = new LoggingHandler(LogLevel.DEBUG);
        // MessageCodec messageCodec = new MessageCodec();
        MessageCodecSharable messageCodec = new MessageCodecSharable();

        NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
        NioEventLoopGroup workerGroup = new NioEventLoopGroup(2);
        ChannelFuture channelFuture = new ServerBootstrap()
                .group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline()
                                .addLast(new ProtocolFrameDecoder())
                                .addLast(loggingHandler)
                                .addLast(messageCodec)
//                                .addLast(loggingHandler)
                                .addLast(new IdleStateHandler(8, 10, 12))
                                // 可以同时作为入站和出站处理器
                                .addLast(new ChannelDuplexHandler() {
                                    @Override
                                    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                                        // 判断是否是IdleStateEvent事件（用于触发用户事件，包含读空闲，写空闲，读写空闲）
                                        if (evt instanceof IdleStateEvent) {
                                            IdleStateEvent event = (IdleStateEvent) evt;
                                            if (event.state() == IdleState.READER_IDLE) {
                                                System.out.println("进入读空闲...");
                                            } else if (event.state() == IdleState.WRITER_IDLE) {
                                                System.out.println("进入写空闲...");
                                            } else if (event.state() == IdleState.ALL_IDLE) {
                                                System.out.println("进入读写空闲...关闭连接");
                                                ctx.channel().close();
                                            }
                                        }
                                    }
                                })
                                .addLast("Server Handler", new ServerMessageHandler());
                    }
                })
                .bind(6666);
        // 监听服务器启动事件
        channelFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                log.debug("聊天服务器启动成功...监听在6666端口");
            }
        });

        // 监听服务器ServerSocketChannel关闭事件，从而停止服务器端的事件循环组中的事件循环
        channelFuture.channel().closeFuture().addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                bossGroup.shutdownGracefully();
                workerGroup.shutdownGracefully();
            }
        });
    }

}
